package com.niuniu.order_consumer.service.impl;

import com.niuniu.order_consumer.exception.NotReportedException;
import com.niuniu.order_consumer.exception.ReportedException;
import com.niuniu.order_consumer.mapper.BedMapper;
import com.niuniu.order_consumer.mapper.RoomMapper;
import com.niuniu.order_consumer.pojo.entity.Bed;
import com.niuniu.order_consumer.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Meng
 * 2022/12/15
 */
@Service
public class RoomServiceImpl implements RoomService {

    @Autowired
    RoomMapper roomMapper;
    @Autowired
    BedMapper bedMapper;

    @Transactional
    @Override
    public Integer allocateRoom(Integer buildingId, Integer gender, Integer classId, List<Integer> uidList) {
        Integer cnt = uidList.size();
        Integer roomId = roomMapper.getARoom(buildingId, gender, classId, cnt);
        if(roomId==null){
            throw new ReportedException("没有空闲房间");
        }
        roomMapper.reduceAvailableBed(roomId,cnt);
        List<Bed> bedList = bedMapper.getAvailableBedList(roomId,cnt);
        if(!cnt.equals(bedList.size())){
            throw new NotReportedException("查询到的床位数与预期不一致");
        }
        List<Bed> newList = new ArrayList<>();
        for(int i = 0;i<cnt;++i){
            Bed bed = bedList.get(i);
            bed.setStatus(1);
            bed.setUid(uidList.get(i));
            newList.add(bed);
        }
        try {
            bedMapper.updateBeds(newList);
        }catch (Exception e){
            throw  new NotReportedException("重复分配床位，事务回滚",e);
        }
        return roomId;
    }
}
